package com.linkhub.oms.component.transactional.config;

import com.alibaba.ttl.threadpool.TtlExecutors;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.RejectedExecutionException;

@Configuration
public class AfterCompletionThreadExecutor {

    private static final int CORE_POOL_SIZE = Runtime.getRuntime().availableProcessors();

    @Bean("afterCompletionExecutor")
    public Executor afterCompletionExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(CORE_POOL_SIZE * 10);
        executor.setMaxPoolSize(CORE_POOL_SIZE * 10 * 2);
        executor.setQueueCapacity(10000 * CORE_POOL_SIZE);
        executor.setKeepAliveSeconds(60);
        executor.setThreadNamePrefix("afterCompletion-async-");
        executor.setRejectedExecutionHandler((r, exe) -> {
            throw new RejectedExecutionException("afterCompletion Executor thread pool is full,throw " +
                    "RejectedExecutionException:" + r.toString() +
                    "; rejected from: " + exe.toString());
        });
        executor.initialize();
        return TtlExecutors.getTtlExecutor(executor);
    }

}
